import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * CREATE TABLE `wish_key_word` (
 `keyword` varchar(128) COLLATE utf8_bin NOT NULL DEFAULT '',
 `reach_text` varchar(64) COLLATE utf8_bin DEFAULT NULL,
 `reach` int(11) DEFAULT NULL,
 `competition_text` varchar(64) COLLATE utf8_bin DEFAULT NULL,
 `competition` int(11) DEFAULT NULL,
 `high_bid` decimal(11,2) NOT NULL DEFAULT '0.00',
 `high_bid_text` varchar(64) COLLATE utf8_bin DEFAULT NULL,
 PRIMARY KEY (`keyword`)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
 */
public class ImportWishKeyWord {
    public static void main(String[] args) throws IOException, SQLException {
        List<JSONObject> list = new ArrayList<JSONObject>();
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost("https://merchant.wish.com/api/login");
        post.setHeader("Referer","https://merchant.wish.com/login");
        post.setHeader("Host","merchant.wish.com");
        post.setHeader("X-XSRFToken","2|d25a4551|8195e257dda9b32cd02a3970ea63e2d1|1511837071");
        post.setHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
        post.setHeader("Cookie","IR_PI=1499321944725-dtakvblbdq; _xsrf=2|d25a4551|8195e257dda9b32cd02a3970ea63e2d1|1511837071; __utma=96128154.2012811805.1499321944.1511256475.1512551929.7; __utmc=96128154; __utmz=96128154.1512551929.7.5.utmcsr=overseas.superseller.cn|utmccn=(referral)|utmcmd=referral|utmcct=/index.html; __utmt=1; rd=\"2|1:0|10:1512972076|2:rd|48:YWMwNWViNDgtY2U5ZS0xMWU3LTg0MjQtMDJjN2RiMzVhM2Vl|7ca759cf7be1ba09682a6b6f67cf70824ed07ea08dd22c004bb6a853af1a01cd\"; remember_me=997471454%40qq.com; __utma=29521315.95696058.1511256581.1512373880.1512972062.5; __utmb=29521315.2.10.1512972062; __utmc=29521315; __utmz=29521315.1511256581.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __zlcmid=htgeXkwChJooOv; RT=\"dm=merchant.wish.com&si=fa552de0-65f7-4db8-864a-75b685e60fe3&ss=1512972015131&sl=7&tt=18432&obo=0&sh=1512972092389%3D7%3A0%3A18432%2C1512972090422%3D6%3A0%3A17333%2C1512972079884%3D5%3A0%3A15993%2C1512972068954%3D4%3A0%3A13176%2C1512972066613%3D3%3A0%3A12096&bcn=%2F%2F36fb61a9.akstat.io%2F&ld=1512972092389\"; bsid=9c25d68ff0074b4fa6feab0825be0ad5");
        post.setHeader("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username","997471454@qq.com"));
        params.add(new BasicNameValuePair("password","cjdz19910915"));
        params.add(new BasicNameValuePair("remember_me","true"));

        HttpEntity httpEntity = EntityBuilder.create().setParameters(params).build();
        post.setEntity(httpEntity);
        HttpResponse httpResponse = httpClient.execute(post);
        Header[] headers = httpResponse.getHeaders("Set-Cookie");
        StringBuffer sb2 = new StringBuffer("");
        for(Header h: headers){
            sb2.append(getCookieFromHttpHeader(h.getValue()));
        }
        sb2.append("_xsrf=2|d25a4551|8195e257dda9b32cd02a3970ea63e2d1|1511837071;");
        String cookie = sb2.toString();
        List<WishKeyWord> ks = new ArrayList<WishKeyWord>();
        for (int i = 1; i <= 7; i++) {
            HttpResponse r = httpClient.execute(getKeywordsPost(cookie,i));
            String result = EntityUtils.toString(r.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(result);
            List<WishKeyWord> rows = jsonObject.getJSONObject("data").getJSONObject("results").getJSONArray("rows").toJavaList(WishKeyWord.class);
            ks.addAll(rows);
        }
        //TODO 入库

        Connection conn = JdbcUtil.getConnection();
        for (WishKeyWord kw:ks){
            try{
            PreparedStatement pstmt = conn.prepareStatement("insert into wish_key_word (keyword,reach_text,reach,competition_text,competition,high_bid,high_bid_text) VALUE (?,?,?,?,?,?,?)");
            pstmt.setString(1,kw.getKeyword());
            pstmt.setString(2,kw.getReach_text());
            pstmt.setInt(3,kw.getReach());
            pstmt.setString(4,kw.getCompetition_text());
            pstmt.setInt(5,kw.getCompetition());
            pstmt.setDouble(6,kw.getHigh_bid());
            pstmt.setString(7,kw.getHigh_bid_text());
            pstmt.execute();
            pstmt.close();
            }catch (Exception e){

            }
        }
        conn.close();
    }


    public static String getCookieFromHttpHeader(String content){
        int i = content.indexOf(";");
        String h =  content.substring(0,i+1);
        return h;
    }


    public static HttpPost getKeywordsPost(String cookie,int page){
        HttpPost post = new HttpPost("https://merchant.wish.com/api/product-boost/keywords/get");
        post.setHeader("Referer","https://merchant.wish.com/login");
        post.setHeader("Host","merchant.wish.com");
        post.setHeader("X-XSRFToken","2|d25a4551|8195e257dda9b32cd02a3970ea63e2d1|1511837071");
        post.setHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
        post.setHeader("Cookie",cookie);
        post.setHeader("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("start",10000*(page-1)+""));
        params.add(new BasicNameValuePair("count","10000"));
        //params.add(new BasicNameValuePair("query",""));
        HttpEntity httpEntity = EntityBuilder.create().setParameters(params).build();
        post.setEntity(httpEntity);
        return post;
    }

}

class WishKeyWord{
    String keyword;
    String reach_text;
    Integer reach;
    String competition_text;
    Integer competition;
    Double high_bid;
    String high_bid_text;

    public String getKeyword() {
        return keyword;
    }

    public void setKeyword(String keyword) {
        this.keyword = keyword;
    }

    public String getReach_text() {
        return reach_text;
    }

    public void setReach_text(String reach_text) {
        this.reach_text = reach_text;
    }

    public Integer getReach() {
        return reach;
    }

    public void setReach(Integer reach) {
        this.reach = reach;
    }

    public String getCompetition_text() {
        return competition_text;
    }

    public void setCompetition_text(String competition_text) {
        this.competition_text = competition_text;
    }

    public Integer getCompetition() {
        return competition;
    }

    public void setCompetition(Integer competition) {
        this.competition = competition;
    }

    public Double getHigh_bid() {
        return high_bid;
    }

    public void setHigh_bid(Double high_bid) {
        this.high_bid = high_bid;
    }

    public String getHigh_bid_text() {
        return high_bid_text;
    }

    public void setHigh_bid_text(String high_bid_text) {
        this.high_bid_text = high_bid_text;
    }
}